<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/12/25
 * Time: 上午9:07
 */

namespace App;

use App\Models\Configure;
use App\Models\RechargeOrder;
use App\Models\RechargeOrderDetail;
use App\Models\RechargeTask;
use App\Models\SmsLog;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OilRecharge
{
    public static function query(RechargeTask $task)
    {
        try {

            DB::beginTransaction();
            $host = 'http://op.juhe.cn/ofpay/sinopec/onlineorder';

            $params         = [
                /**
                 * 10000(中石化50元加油卡)[暂不支持]
                 * 10001(中石化100元加油卡)
                 * 10002(中石化200元加油卡)
                 * 10003(中石化500元加油卡)
                 * 10004(中石化1000元加油卡)
                 * 10007(中石化任意金额充值)[暂不支持]
                 * 10008(中石油任意金额充值))
                 */
                'proid'       => $task->pro_id,
                'cardnum'     => $task->card_num,
                'orderid'     => $task->sn,
                'game_userid' => $task->card_no,
                'gasCardTel'  => $task->card_mobile,
                'gasCardName' => $task->card_name,

                // （1:中石化、2:中石油；默认为1
                'chargeType'  => $task->card_type,
                'key'         => Configure::getByKey('juhe_appkey'),
            ];

            $openid         = Configure::getByKey('juhe_openid');
            $params['sign'] = md5($openid . $params['key'] . $params['proid'] . $params['cardnum'] . $params['game_userid'] . $params['orderid']);

            $http = new Client();
            $response = $http->post($host, [
                'query' => $params
            ]);
            if ($response->getStatusCode() == 200) {
                $result = json_decode($response->getBody(), true);

                if ($result['error_code'] == 0) {

                    // task->status 0待充值，1请求充值成功，2请求充值失败，4充值失败，9充值成功
                    $task->status = 1;
                    $task->result = $response->getBody();
                    $task->save();

                    /*$detail = $task->detail;
                    if ($detail) {
                        $detail->is_paid = 1;
                        $detail->paid_at = Carbon::now()->toDateTimeString();
                        $detail->save();
                    } else {
                        $order = $task->order;
                        $order->status = RechargeOrder::STATUS_DONE;
                        $order->save();
                    }*/

                } else {
                    $task->status = 2;
                    $task->result = $response->getBody();
                    $task->save();
                    DB::commit();
                    Log::error('请求聚合充值接口失败, 详情：' . $result['reason']);

                    // 短信通知
                    $adminMobile = Configure::getByKey('admin_mobile');
                    if ($adminMobile) {
                        Sms::send($adminMobile, [
                            'order_id' => $task->order->id
                        ], Sms::TPL_RECHARGE_FAIL);
                    }
                }

            } else {
                /*$task->status = 2;
                $task->result = $response->getBody();
                $task->save();*/
                DB::commit();
                Log::error('请求聚合充值接口失败');
                return false;
            }

            DB::commit();
            return true;
        } catch (\Exception $e) {
            Log::error($e);
            DB::rollBack();
            return false;
        }
    }

    public static function syncStatus(RechargeTask $task)
    {
        try {

            DB::beginTransaction();
            $host = 'http://op.juhe.cn/ofpay/sinopec/sordersta';

            $params = [
                'key' => Configure::getByKey('juhe_appkey'),
                'orderid' => $task->sn,
                'timestamp' => time(),
            ];

            // sign = md5(OpenID+key+orderid+timestamp)
            $openid         = Configure::getByKey('juhe_openid');
            $params['sign'] = md5($openid . $params['key'] .  $params['orderid'] . $params['timestamp']);

            $http = new Client();
            $response = $http->post($host, [
                'query' => $params
            ]);
            if ($response->getStatusCode() == 200) {
                $result = json_decode($response->getBody(), true);
                if ($result['error_code'] == 0 && $result['result']['game_state'] == 1) {
                    // task->status 0待充值，1请求充值成功，2请求充值失败，4充值失败，9充值成功
                    $task->status = 9;
                    $task->result = $response->getBody();
                    $task->save();

                    $detail = $task->detail;
                    if ($detail) {
                        $detail->is_paid = 1;
                        $detail->paid_at = Carbon::now()->toDateTimeString();
                        $detail->save();
                        if ($detail->current_month == $detail->total_month) {
                            $task->order->status = RechargeOrder::STATUS_DONE;
                            $task->order->save();
                        }
                    } else {
                        Log::info($task);
                        Log::info($task->order);
                        $order = $task->order;
                        $order->status = RechargeOrder::STATUS_DONE;
                        $order->save();
                    }

                    // 发送成功短信
                    Sms::send($task->card_mobile, [
                        'card_no' => substr($task->card_no, -6),
                        'amount' => $task->amount,
                    ], Sms::TPL_RECHARGE_SUCCESS);

                } elseif ($result['result']['game_state'] == 9) {
                    $task->status = 4;
                    $task->result = $response->getBody();
                    $task->save();

                    // TODO 需要人工介入

                    Log::error('请求聚合充值接口失败, 详情：' . $result['reason']);
                } else {
                    $task->result = $response->getBody();
                    $task->save();
                }

                Log::info('task_id:' . $task->id  . ':' . $response->getBody());

                DB::commit();

            } else {
                Log::error('请求聚合充值接口失败');
            }

        } catch (\Exception $e) {
            Log::error($e);
            DB::rollBack();
            return false;
        }
    }
}